package org.example.forum.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.config.AppConfig;
import org.example.forum.model.Article;
import org.example.forum.model.Board;
import org.example.forum.model.User;
import org.example.forum.services.IArticleService;
import org.example.forum.services.IBoardService;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/article")
@Tag(name = "文章接口")
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IBoardService boardService;

    /**
     * 发布新帖子
     * @param boardId 板块Id
     * @param title 标题
     * @param content 文章内容
     * @return
     */
    @Operation(summary = "发布新帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @Parameter(ref = "板块Id") @RequestParam("boardId") @NonNull Long boardId,
                            @Parameter(ref = "标题") @RequestParam("title") @NonNull String title,
                            @Parameter(ref = "文章内容") @RequestParam("content") @NonNull String content ) {
        //校验用户禁言状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            //说明用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //板块的校验
        Board board = boardService.selectById(boardId.longValue());
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //封装文章对象
        Article article = new Article();
        article.setTitle(title);            //标题
        article.setContent(content);        //正文
        article.setBoardId(boardId);        //板块id
        article.setUserId(user.getId());    //作者id
        //调用service
        articleService.create(article);
        //响应
        return AppResult.success();
    }

    @Operation(summary = "获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@Parameter(ref = "板块id")@RequestParam(value = "boardId",required = false) Long boardId) {
        //如果boardId为空则查询所有帖子
        //如果不为空则查询boardId板块下的帖子

        //定义返回的集合
        List<Article> articles;
        if (boardId == null) {
            //查询所有
            articles= articleService.selectAll();
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }
        //非空判断
        if (articles == null) {
            //如果结果集为空，则创建一个空集合返回就可以了
            articles = new ArrayList<>();
        }
        //响应结果
        return AppResult.success(articles);
    }

    @Operation(summary = "根据帖子id获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                        @Parameter(ref = "帖子id")@RequestParam("id")@NonNull Long id){
        //从session中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service层获取帖子详情
        Article article = articleService.selectDetailById(id);
        if (article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断是否为作者
        if (user.getId() == article.getUserId()) {
            //标识为作者
            article.setOwn(true);
        }
        return AppResult.success(article);
    }


    @Operation(summary = "根据id修改帖子内容")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @Parameter(ref = "帖子id")@RequestParam("id")@NonNull Long id,
                            @Parameter(ref = "帖子标题")@RequestParam("title")@NonNull String title,
                            @Parameter(ref = "帖子正文")@RequestParam("content")@NonNull String content) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //要判断用户状态是否禁言以及是否为帖子作者
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectDetailById(id);
        //校验帖子是否有效  (|| article.getDeleteState() == 1
        if (article == null|| article.getDeleteState() == 1) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断是否是作者
        if (!user.getId().equals(article.getUserId())) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //判断帖子状态
        if (article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        //调用service
        articleService.modify(id, title, content);
        //打印日志
        log.info("更新帖子成功，Article id = "+id+", User id = "+user.getId());

        return AppResult.success();
    }

    @Operation(summary = "点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @Parameter(ref = "帖子id")@RequestParam("id")@NonNull Long id) {
        //校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户状态是否被禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //调用service
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    @Operation(summary = "删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @Parameter(ref = "帖子id")@RequestParam("id")@NonNull Long id){
        //校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            //代表用户禁言了
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            //表示帖子已删除
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //校验当前登录的用户是不是作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //调用service执行方法
        articleService.deleteById(id);
        //操作成功返回正常描述
        return AppResult.success();
    }

    @GetMapping("/getAllByUserId")
    @Operation(summary = "获取用户帖子列表")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                    @Parameter(ref = "用户id")@RequestParam(value = "userId",required = false) Long userId) {
        //如果userId为空，从session中获取当前登录的用户的userId
        if (userId == null) {
            HttpSession session = request.getSession(false);
            //获取user对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        List<Article> result = articleService.selectByUserId(userId);
        return AppResult.success(result);
    }
}
